package org.gnomus.data;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Transaction;

import java.util.ArrayList;
import java.util.List;

public class lesson extends object {

    public lesson(Entity e) {
        super(e);
        setTitle((String) e.getProperty("title"));
        setSubject((String) e.getProperty("subject"));
        setItems(getItems(this));
    }

    // constructor called when creating a new lesson with no items yet.
    public lesson(String title, String subject) {
        super("lesson");
        setTitle(title);
        setSubject(subject);
    }

/*
    public lesson(JSONObject jo) {
        super("lesson");
        try {
            setTitle(jo.getString("title"));
            setSubject(jo.getString("subject"));
        } catch (JSONException e) {
            throw new Error(e);
        }
    }
*/

    public void delete() {
        Transaction txn = store.beginTransaction();
        try {
            for (item itm : getItems()) {
                itm.delete();
            }
            link.delete(key);
            store.delete(key);
            txn.commit();
        } finally {
            if (txn.isActive()) {
                txn.rollback();
            }
        }
    }

    public static lesson fetch(String id) {
        Entity e = store.get("lesson", id);
        if (e == null) { return null; }

        lesson lsn = new lesson(e);
        return lsn;
    }


    public void setTitle(String title) {
        put("title", title);
    }

    public String getTitle() {
        return (String) get("title");
    }

    public void setSubject(String subject) {
        put("subject", subject);
    }

    public String getSubject() {
        return (String) get("subject");
    }

    public void setItems(List<item> items) {
        put("items", items);
    }

    public List<item> getItems() {
        return (List<item>) get("items");
    }

    public static List<item> getItems(lesson lsn) {
        List<item> items = new ArrayList<item>();
        for (link lnk : link.fetch("lesson", lsn.key, "item", null)) {
            Entity i = lnk.getTarget();
            if (i == null) { continue; }
            items.add(new item(i));
        }
        return items;
    }
}
